# app/controllers/family/account.py
from typing import Optional, List, Dict, Any, Tuple
from datetime import datetime
from decimal import Decimal

from app.core.crud import CRUDBase
from app.services.family.account import account_service
from app.schemas.family.account import AccountCreate, AccountUpdate
from app.models.family.account import AccountRecord
from app.utils.app_log import logger


class AccountController():
    """账目管理控制器"""
    
    def __init__(self):
        self.service = account_service

    async def list_items(
        self, 
        page: int = 1, 
        page_size: int = 10, 
        search: Optional[str] = None,
        order: Optional[List[str]] = None
    ) -> Tuple[int, List[AccountRecord]]:
        """获取账目记录列表"""
        # 直接调用 service，异常由全局处理器处理
        return await self.service.list_by_user(page, page_size, search, order or ["-created_at"])

    async def create_item(self, obj_in: AccountCreate) -> AccountRecord:
        """添加账目记录"""
        # 数据验证交给 service
        return await self.service.add_record(obj_in)

    async def get_statistics(
        self, 
        start_datetime: datetime, 
        end_datetime: datetime
    ) -> Dict[str, Any]:
        """获取统计数据"""
        return await self.service.get_statistics(start_datetime, end_datetime)

    async def get_category_stats(
        self, 
        start_datetime: datetime, 
        end_datetime: datetime, 
        type_: Optional[str] = None
    ) -> List[Dict[str, Any]]:
        """获取分类统计数据"""
        return await self.service.get_category_stats(start_datetime, end_datetime, type_)

    async def update_item(self, id: int, obj_in: AccountUpdate) -> AccountRecord:
        """更新账目记录"""
        return await self.service.update_record(id, obj_in)

    async def remove_item(self, id: int) -> bool:
        """删除账目记录"""
        return await self.service.delete_record(id)

    async def get_monthly_trend(self, months: int = 6) -> List[Dict[str, Any]]:
        """获取月度趋势数据"""
        return await self.service.get_monthly_trend(months)

    async def get_item(self, id: int) -> AccountRecord:
        """获取单个账目记录详情"""
        # 使用基类的 get 方法，不存在时会抛出异常
        return await self.service.get(id=id)


account_controller = AccountController()